//
//  XLVideoSetController.m
//  XiangLove
//
//  Created by 宋振 on 2018/8/9.
//  Copyright © 2018年 BAOMIHUA.COM. All rights reserved.
//

#import "XLVideoSetController.h"
#import "SHShortVideoViewController.h"
#import "XLVideoSetCell.h"

#import "VideoRecordViewController.h"

//数据模型
#import "XLCommitVideoSetModel.h"

#import <SVProgressHUD.h>

#import <MJRefresh.h>

#import "XLHTTPSessionManager+Analytics.h"
#import "CustomerAVPlayerView.h"

//视频集合
#define kRequestVideoUrl    @"/api/v2/DynamicVideo/GetAnchorDynamicVideoV2"

@interface XLVideoSetController ()<UITableViewDelegate,UITableViewDataSource,CustomerDelegate>

@property (nonatomic, strong) UITableView *  tableView;

//数据源
@property (nonatomic, strong) NSMutableArray *  dataSources;

//视频集数据源
@property (nonatomic, strong) NSArray *  videoArray;

//
@property (nonatomic, strong) CustomerAVPlayerView *  customerView;

@end

@implementation XLVideoSetController
{
    //分页
    NSInteger page;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = @"视频集";
    
    [self showBackButton:^{
        
        if (self.isRefresh) {
            self.isRefresh(YES);
        };
        
        [self.navigationController popViewControllerAnimated:YES];
        
    }];
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    page = 1;
    
    //设置界面显示
    [self initUI];
    
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    page = 1;
    
    //请求视频集
    [self requestVideoSet];
}

#pragma mark        -   -   - InitUI -  -   -

/**
 主界面显示
 */
- (void)initUI
{
    self.tableView = [[UITableView alloc] initWithFrame:CGRectZero];
    self.tableView.backgroundColor = RGB(243, 243, 243);
    
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    [self.view addSubview:self.tableView];
    
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self.view);
        make.top.equalTo(self.view.mas_top);
        make.bottom.equalTo(self.view.mas_bottom).offset(-48);
    }];
    
    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        
        //重新加载数据
        [self requestVideoSet];
        
    }];
    
    //注册
    [self.tableView registerClass:[XLVideoSetCell class] forCellReuseIdentifier:NSStringFromClass([XLVideoSetCell class])];
    
    //temp
//    [self.dataSources addObjectsFromArray:@[@"1",@"2",@"3",@"4"]];
    
    /**
     添加上传按钮
     */
    UIButton *upVideo = [UIButton buttonWithType:(UIButtonTypeCustom)];
    upVideo.frame = CGRectMake(0, 0, ScreenWidth, 48);
    upVideo.backgroundColor = RGB(255, 187, 1);
    [upVideo setTitle:@"上传" forState:(UIControlStateNormal)];
    [upVideo addTarget:self action:@selector(upVideoAction:) forControlEvents:(UIControlEventTouchUpInside)];
    
    [self.view addSubview:upVideo];
    
    [upVideo mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self.view);
        make.top.equalTo(self.tableView.mas_bottom);
        make.bottom.equalTo(self.view.mas_bottom);
    }];
}

#pragma mark    - - - 数据请求 - - -

/**
 请求视频集合
 */
- (void)requestVideoSet
{
    [[[XLHTTPSessionManager sharedManager] XLV2GET:kRequestVideoUrl parameters:@{
                                                                                 @"UserID":[[XLAccountManager shareInstance] model].Id,
                                                                                 @"pageSize":@"10",
                                                                                 @"pageIndex":@(page)
                                                                                 } resultClass:[XLCommitVideoSetModel class]] subscribeNext:^(id x) {
        
        //如果是上拉刷新 重置所有数据
        if (page == 1) {
            
            if (self.dataSources.count > 0) {
                [self.dataSources removeAllObjects];
            }
            
        }
        
        [self.dataSources addObjectsFromArray:x];
        
        if (self.dataSources.count > 0) {
            page++;
        }
        
        if (self.dataSources.count < page *10) {
            self.tableView.mj_footer.hidden = YES;
        }else{
            self.tableView.mj_footer.hidden = NO;
        }
        
        [self.tableView.mj_footer endRefreshing];
        
        [self.tableView reloadData];
        
        
    } error:^(NSError *error) {
        
        NSLog(@"视频集请求失败");
        [self.tableView.mj_footer endRefreshing];
        
    }];
}

#pragma mark        - - - Actions - - -

/**
 按钮删除事件
 */
- (void)clickCell:(NSIndexPath *)indexPath
{
    XLCommitVideoSetModel *deleteModel = self.dataSources[indexPath.row];
    
    //删除请求
    [SVProgressHUD showWithStatus:@"正在删除..."];
    
    [[[XLHTTPSessionManager sharedManager] XLV2GET:@"/Api/v2/DynamicVideo/DeleteDynamicVideo" parameters:@{@"videoId":K_DEFULT(deleteModel.Id)} resultClass:nil] subscribeNext:^(id x) {
        NSLog(@"删除成功！");
        [SVProgressHUD dismiss];
        [self.dataSources removeObjectAtIndex:indexPath.row];
        [self.tableView reloadData];
    } error:^(NSError *error) {
        NSLog(@"删除失败！");
    }];
    
    
    
}

/**
 上传视频事件
 */
- (void)upVideoAction:(UIButton *)sender {
    
//    VideoRecordViewController * recordVC  = [[VideoRecordViewController alloc] init];
//    recordVC.ComeFromEditVC = YES;
//    [self.navigationController pushViewController:recordVC animated:YES];

    
}


#pragma makr        - - - UITableView代理和数据源 -   -   -

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dataSources.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    XLVideoSetCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([XLVideoSetCell class]) forIndexPath:indexPath];
    
    XLCommitVideoSetModel *model = self.dataSources[indexPath.row];
    
    cell.model = model;
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 100;
}

//设置滑动
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    return YES;
}

- (NSArray<UITableViewRowAction *> *)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewRowAction *deleteAction = [UITableViewRowAction rowActionWithStyle:(UITableViewRowActionStyleDestructive) title:@"删除" handler:^(UITableViewRowAction * _Nonnull action, NSIndexPath * _Nonnull indexPath) {
        
        //删除事件
        [self clickCell:indexPath];
        
    }];
    
    deleteAction.backgroundColor = [UIColor redColor];
    
    return @[deleteAction];
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:(UITableViewRowAnimationTop)];
    }
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    XLCommitVideoSetModel *model = self.dataSources[indexPath.row];
    
    if ([model.Status isEqualToString:@"1"] || [model.Status isEqualToString:@"2"]) {
        
        _customerView = [[CustomerAVPlayerView alloc] initWithFrame:CGRectMake(0.0f, 0, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height) urlPath:K_DEFULT(model.PlayUrl) isFileUrl:NO];
        _customerView.Delegate = self;
        
        [_customerView.player play];
        [_customerView.controlView setPlayButtonSelected:YES];
        [[UIApplication sharedApplication].keyWindow addSubview:_customerView];
        
        [self analyticsEvent2];
        
    }
}

#pragma mark - CustomerDelegate
- (void)clickBackBtnVideoPlay {
    [_customerView.player pause];
    [_customerView removeFromSuperview];
    _customerView = nil;
}

- (void)videoIsStartToPlay {
    
}

- (void)analyticsEvent2 {
    NSDictionary *attributes = [self genrateAttributes];
    if (attributes.allKeys.count == 2) {
        [MobClick event:@"xl_clickvideo" attributes:attributes];
        [[[XLHTTPSessionManager sharedAnalyticsManager] analyticsModule:@"xl_myindex" action:@"xl_clickvideo" userId:attributes[@"userid"] camgirlId:attributes[@"camgirlid"]] subscribeNext:^(id x) {
        } error:^(NSError *error) {
        }];
    }
}

#pragma mark - 统计
- (NSDictionary *)genrateAttributes {
    NSMutableDictionary *attributes = [NSMutableDictionary dictionary];
    if ([[XLAccountManager shareInstance] model].Id) {
        [attributes setObject:[[XLAccountManager shareInstance] model].Id ?: @"" forKey:@"userid"];
    }
    if (self.userId) {
        [attributes setObject:self.userId ?: @"" forKey:@"camgirlid"];
    }
    return attributes.copy;
}



#pragma mark    - - - 懒加载 - - -

- (NSMutableArray *)dataSources
{
    if (!_dataSources) {
        self.dataSources = [NSMutableArray arrayWithCapacity:1];
    }
    
    return _dataSources;
}


@end
